<script setup lang='ts'>
import { delArticleAPI, getArticleListAPI, getChannelListAPI } from '@/apis';
import type { ArticleItem, ArticleParams, ChannelItem } from '@/types';
import { ArrowRight, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

// 获取频道列表
const channelList = ref<ChannelItem[]>()
onMounted(async () => {
  const res = await getChannelListAPI()
  channelList.value = res.data.channels
  // console.log(channelList.value);
})
// 定义获取文章的参数
const articleParamsForm = ref<ArticleParams>({
  status: '',
  channel_id: 0,
  begin_pubdate: '',
  end_pubdate: '',
  page: 1,
  per_page: 10
})
// 定义一个数组来存储日期
const dateArr = ref([])
//监听日期数组变化并存储
watch(dateArr, (value) => {
  if (value) {
    articleParamsForm.value.begin_pubdate = value[0]
    articleParamsForm.value.end_pubdate = value[1]
  } else {
    articleParamsForm.value.begin_pubdate = ''
    articleParamsForm.value.end_pubdate = ''
  }
})
// 表单校验
const articleParamsRef = ref<FormInstance>()
const articleParamsRules = ref<FormRules<ArticleParams>>({
  channel_id: [
    { required: true, message: '请选择频道', trigger: 'change' }
  ],
  end_pubdate: [
    { required: true, message: '请选择日期', trigger: 'blur' }
  ]
})
// 提交信息筛选表单
const total = ref(0)
const articleList = ref<ArticleItem[]>()
const onSubmit = () => {
  articleParamsRef.value?.validate(async (res) => {
    if (res) {
      try {
        const res = await getArticleListAPI(articleParamsForm.value)
        console.log(res);
        articleList.value = res.data.results
        total.value = res.data.total_count

      } catch (error) {
        console.log('信息筛选表单:', error)
      }
    }
  })
}

// 渲染表格
// 修改 formatStatus 函数，确保返回值不会是 undefined
const formatStatus = (row: ArticleItem) => {
  switch (row.status) {
    case 0:
      return '草稿';
    case 1:
      return '待审核';
    case 2:
      return '审核通过';
    case 3:
      return '审核失败';
    default:
      return '未知状态'; // 添加默认返回值
  }
}
// 删除功能:
const onDel = (id: string) => {
  ElMessageBox.confirm('此操作将删除该文章, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 注意：这里必须添加 await 等待删除请求结束，再获取文章列表
    await delArticleAPI(id, { draft: false })
    // 重新获取文章列表（刷新表格）
    const res = await getArticleListAPI(articleParamsForm.value)
    articleList.value = res.data.results
    total.value = res.data.total_count
    // 删除成功轻提示
    ElMessage.success('文章删除成功!')
  }).catch(() => {
    // 用户点击取消时触发，但是不能省略 catch，否则控制台会报错
  })
}
const router = useRouter()
const onEdit = (id: number) => {
  router.push(`/publish/${id}`)
}

</script>

<template>
  <el-card style="width:98%">
    <template #header>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>内容管理</el-breadcrumb-item>
      </el-breadcrumb>
    </template>

    <el-form label-width="80px" ref="articleParamsRef" :rules="articleParamsRules" :model="articleParamsForm">

      <el-form-item label="状态：">
        <!-- 文章状态，0-草稿，1-待审核，2-审核通过，3-审核失败，不传为全部 -->
        <el-radio-group v-model="articleParamsForm.status">
          <el-radio value="">全部</el-radio>
          <el-radio :value="0">草稿</el-radio>
          <el-radio :value="1">待审核</el-radio>
          <el-radio :value="2">审核通过</el-radio>
          <el-radio :value="3">审核失败</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="频道：" prop="channel_id">
        <el-select clearable placeholder="请选择" style="width: 240px" v-model="articleParamsForm.channel_id">
          <!-- 根据请求的频道列表来循环渲染 -->
          <el-option v-for="item in channelList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="日期：" prop="end_pubdate" style="width: 400px;">
        <el-date-picker v-model="dateArr" type="daterange" range-separator="To" start-placeholder="Start date"
          end-placeholder="End date" value-format="YYYY-MM-DD" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">筛选</el-button>
      </el-form-item>
    </el-form>

  </el-card>
  {{ articleParamsForm }}

  <!-- 查询结果 -->
  <el-card style="width:98%;margin-top: 30px;">
    <template #header>
      根据筛选条件共查询到 {{ total }} 条结果：
    </template>

    <el-table style="width: 100%" :data="articleList">
      <!-- <el-table-column label="选择" type="selection" /> -->
      <!-- 单图 -->
      <el-table-column label="封面" width="125">
        <template #default="scope">
          <el-image :src="scope.row.cover.images[0]" alt="封面" style="width: 100px; height: 100px" fit="cover"
            :preview-src-list="scope.row.cover.images" />
        </template>
      </el-table-column>

      <el-table-column prop="title" label="标题" width="120" />
      <el-table-column prop="status" label="状态" :formatter="formatStatus" />
      <el-table-column prop="pubdate" label="发布时间" width="150" />
      <el-table-column prop="read_count" label="阅读数" />
      <el-table-column prop="comment_count" label="评论数" />
      <el-table-column prop="like_count" label="点赞数" />

      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <!-- <el-icon><Edit /></el-icon> -->
          <!-- <el-icon><Delete /></el-icon> -->
          <el-button type="primary" :icon="Edit" circle @click="onEdit(row.id)" />
          <el-button type="danger" :icon="Delete" circle @click="onDel(row.id)" />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top: 25px;" v-model:current-page="articleParamsForm.page"
      v-model:page-size="articleParamsForm.per_page" :page-sizes="[2, 5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @change="onSubmit" />

  </el-card>
</template>

<style scoped></style>
